{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.tree import DecisionTreeClassifier  # 分类树\n",
    "from sklearn.tree import export_graphviz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_csv(\"titanic.csv\",\n",
    "                   index_col=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 特征：年龄age 633有值； 性别sex 完整； 舱位pclass 完整\n",
    "X = data[[\"age\", \"sex\", \"pclass\"]].copy()\n",
    "y = data[\"survived\"]  # 1 活  0 死"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据清洗\n",
    "# 年龄为空 填充一个 均值/众数/中位\n",
    "# print(\"年龄的均值/众数/中位\", X[\"age\"].mean(), X[\"age\"].mode()[0], X[\"age\"].median())\n",
    "\n",
    "X.fillna({\"age\": X[\"age\"].median()}, inplace=True)\n",
    "# 将特征非数值变成数值\n",
    "# 舱位转换为数值\n",
    "X[\"pclass\"] = X[\"pclass\"].str[0]\n",
    "X[\"pclass\"] = X[\"pclass\"].astype(int)\n",
    "\n",
    "# 性别有不同的取值\n",
    "# print(X[\"sex\"].unique())\n",
    "\n",
    "X[\"sex\"] = (X[\"sex\"] == 'male').astype(int)\n",
    "\n",
    "# print(\"特征\\n\", X)\n",
    "feature_names = X.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X,\n",
    "    y,\n",
    "    random_state=1,\n",
    "    test_size=0.2,\n",
    "    stratify=y\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "准确率 0.8060836501901141\n"
     ]
    }
   ],
   "source": [
    "dt = DecisionTreeClassifier(max_depth=5)\n",
    "\n",
    "dt.fit(X_train, y_train)\n",
    "\n",
    "print(\"准确率\", dt.score(X_test, y_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "age       18.0\n",
      "sex        0.0\n",
      "pclass     3.0\n",
      "Name: 695, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "XX = X_train.iloc[9, :]\n",
    "print(XX)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
